﻿import Vue from "vue";
import layer from "./layui/lay/modules/layer.js";
import $ from 'jquery';
import {
    serverPath
} from './config.js';
import store from 'store';


function nextTick() {
    var promise = new Promise((resolve, reject) => {
        Vue.nextTick(() => {
            resolve();
        });
    });
    return promise;
}

function setPageNumber(pager) {
    var pageIndex = pager.pageIndex;
    var pageCount = pager.pageCount;
    var index = 0;
    var count = 0;
    if (pageIndex < 4) {
        count = 5;
        index = 1;
    } else {
        index = pageIndex - 2;
        count = pageIndex + 2;
    }
    pager.pageNumber = [];
    for (var i = index; i <= count && i <= pageCount; i++) {
        pager.pageNumber.push(i);
    }
}

function open(options) {
    let promise = new Promise((resolve, reject) => {
        var _options = {
            type: 2,
            shadeClose: true,
            shade: 0.8,
            maxmin: true,
            area: ['90%', '70%'],
            end: () => {
                resolve();
            }
        };
        for (var item in options) {
            if (item !== "end")
                _options[item] = options[item];
        }
        layer.open(_options);
    });
    return promise;
}

function load() {
    layer.load(2);
    NProgress.start();
}

function closeAll() {
    layer.closeAll();
    NProgress.done();
}

function confirm(title) {
    let promise = new Promise((resolve, reject) => {
        layer.confirm(title, {
            title: '提示'
        }, (index) => {
            resolve();
            layer.close(index);
        });
    });
    return promise;
}

function msg(message) {
    let promise = new Promise((resolve, reject) => {
        layer.msg(message, () => {
            resolve();
        });
    });
    return promise;
}

function close() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index)
}

function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
};
function getQueryStringFromHash(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var path = window.location.hash.split('?');
    if (path.length == 2) {
        var r =path[1].match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }
    else{
        return null;
    }
}

function getFormData(selector) {
    var data = {};
    var _data = $(selector).serializeArray();
    for (var index in _data) {
        data[_data[index].name] = _data[index].value;
    }
    return data;
}

function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

function connect(url) {
    return new Promise((resolve, reject) => {
        var server = new WebSocket(url);
        server.onopen = function () {
            resolve(server);
        };
        server.onerror = function (err) {
            reject(err);
        };
    });
}

function prepareRequest(request) {
    return new Promise((resolve, reject) => {

        $(document)[0].dispatchEvent(new Event('ajax:start'));

        if (store.get("AuthCode")) {
            request.set('Authorization', `Bearer ${store.get("AuthCode")}`);
        }

        request.timeout({
            response: 10 * 1000
        });
        request.end(function (err, res) {
            $(document)[0].dispatchEvent(new Event('ajax:end'));

            if (request.xhr.responseURL != request.url) {
                //window.location.href = `${serverPath}login.html`;
                return;
            }
            if (err && err.timeout) {
                reject(err);
            } else {
                resolve(res);
            }
        });
    });
}


function serviceInterceptor() {
    return function (target, key, descriptor) {
        const method = descriptor.value;
        descriptor.value = (...args) => {
            var result = method.apply(target, args);
            return result;
        }
        return descriptor;
    }
}
export {
    nextTick,
    setPageNumber,
    open,
    load,
    closeAll,
    confirm,
    msg,
    close,
    getQueryString,
    getFormData,
    getObjectURL,
    connect,
    prepareRequest,
    serviceInterceptor,
    getQueryStringFromHash
}